#include "networker.h"

#include <QDir>
#include <QEventLoop>
#include <QFile>
#include <QIODevice>
#include <QJsonParseError>
#include <QNetworkAccessManager>
#include <QStandardPaths>
#include <QTextCodec>


NetWorker::NetWorker(QObject *parent) :
    QObject(parent),
    d(new NetWorker::Private(this))
{
    connect(d->manager, &QNetworkAccessManager::finished,this, &NetWorker::testFinished);

    qDebug()<<"init net";
    //TODO 初始化
    urlMap.insert("station_name","https://kyfw.12306.cn/otn/resources/js/framework/station_name.js");
    md5Map.insert("station_name","dceae511b2276ea3a1a4798485952995");

    urlMap.insert("station_qss","https://kyfw.12306.cn/otn/resources/js/query/qss.js");
    md5Map.insert("station_qss","dceae511b2276ea3a1a4798485952995");

}

NetWorker *NetWorker::instance()
{
    static NetWorker netWorker;
    return &netWorker;
}

NetWorker::~NetWorker()
{
    delete d;
    d = 0;
}

QNetworkReply * NetWorker::get(QString type)
{
    QEventLoop loop;
    urlType = type;
    QString openUrl=getAPIUrl();
    qDebug()<<openUrl;


//    d->manager->setCookieJar(cookies);
    QNetworkRequest mRequest;
    QSslConfiguration config;
    config.setPeerVerifyMode(QSslSocket::VerifyNone);
    config.setProtocol(QSsl::TlsV1_2);
    mRequest.setSslConfiguration(config);
    mRequest.setUrl(openUrl);
    mRequest.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);
    repl = d->manager->get(mRequest);
    connect(repl, &QNetworkReply::readyRead,this, &NetWorker::testRead);
    connect(repl,&QNetworkReply::finished,&loop,&QEventLoop::quit);
    loop.exec();
    return repl;
}

void NetWorker::testFinished(QNetworkReply *result)
{

    qDebug()<<result->url().toString();

//    //文件存储
//    QString writable = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
//    QDir dir(writable);
//    if(!dir.exists()){
//        qDebug() << "mkpath writable.";
//        dir.mkpath(writable);
//    }

//    QFile *tempFile = new QFile;
//    QString fileName = QString(writable+"/file.js");
//    //此时，路径下没有fileName文件，使用下面代码在当前路径下创建文件
//    tempFile->setFileName(fileName);
//    if(tempFile->exists(fileName)){
//        tempFile->remove();
//    }
//    if(tempFile->open(QIODevice::WriteOnly|QIODevice::Text))
//    {
//        tempFile->write(result->readAll());
//    }else {
//        qDebug()<<fileName+"打开失败";
//    }
//    tempFile->close();

//    qDebug()<<"testFinished start ";
//    qDebug()<<resultStr.length();

    QString oldMd5 = getMD5Url();
    qDebug()<<oldMd5;
    QByteArray bytePwdMd5 = QCryptographicHash::hash(resultStr, QCryptographicHash::Md5);
    QString newMd5 = bytePwdMd5.toHex();
    qDebug()<<newMd5;

    //如果md5改变后，则更新文件，增加后续的处理
    if(oldMd5!=newMd5){

        //TODO 存储
        if("station_name"==urlType){
            qDebug() << "station_name";

            QString tmpStations = QString(resultStr);
            QString tmp_start = "var station_names ='@";
            QString tmp_end = "';";
            tmpStations.replace(0,tmp_start.length(),"");
            tmpStations.replace(tmpStations.length()-tmp_end.length(),tmp_end.length(),"");
            QList<QString> resultList = tmpStations.split("@");

            QListIterator<QString> i(resultList);
             while (i.hasNext()) {
                 qDebug() << i.next();
             }
        }

        if("station_qss"==urlType){
            qDebug() << "station_qss";

            QString tmpStations = QString(resultStr);
            QString tmp_start = "var citys = ";
            tmpStations.replace(0,tmp_start.length(),"");

            QJsonParseError error;
            QJsonDocument jsonDocument = QJsonDocument::fromJson(tmpStations.toLatin1(), &error);
            qDebug()<<"start";
            if (error.error == QJsonParseError::NoError) {
                qDebug()<<" no error";
                if (!(jsonDocument.isNull() || jsonDocument.isEmpty()) && jsonDocument.isObject()) {
                    qDebug()<<"is Object";
                    QVariantMap data = jsonDocument.toVariant().toMap();
                    qDebug()<<data[QLatin1String("debug")].toString();
                }
            }else{
                qDebug()<<error.error;
                qDebug()<<error.errorString();
            }
        }
    }

    resultStr.clear();
    qDebug()<<"testFinished end ";
}
void NetWorker::testRead()
{
//    resultStr.append(repl->readAll());
}
void NetWorker::quit(QNetworkReply *reply)
{
    qDebug()<<"quit end ";
}

QString NetWorker::getAPIUrl(){
    return urlMap.value(urlType);
}

QString NetWorker::getMD5Url(){
    return md5Map.value(urlType);
}

